<script setup name="TreeLeft">
import {dictGetList} from "@/api/sys/dict";
import {getCurrentInstance, onMounted, reactive} from "vue";

const {proxy} = getCurrentInstance();
const props = defineProps({
  // 父类
  dict: {
    type: String,
    default: null
  }
});

let pd = reactive({
  dictList: [],
  name: "",
  queryParams: {
    ancestors: null,
    code: null
  }
});

function getList() {
  dictGetList({ancestors:pd.queryParams.ancestors}).then(res => {
    pd.dictList = proxy.handleTree(res.data, 'id', 'parentId', 'children');
  });
}

/** 根据名称筛选树 */
watch(() => pd.name, val => {
  if (pd.dictList.length === 0) {
    return;
  }
  proxy.$refs["dictRef"].filter(val);
}, {deep: true, immediate: true});

/** 根据名称筛选树 */
watch(props.dict, val => {
  initDictLeftTree();
}, {deep: true, immediate: true});

// 初始化数据展示
function initDictLeftTree() {
  if (pd.dictList.length > 0) {
    return;
  }
  pd.queryParams.code = props.dict;
  dictGetList({code:pd.queryParams.code}).then(res => {
    if ( res.data[0].parentId === 1 ){
      pd.queryParams.ancestors = res.data[0].id;
      getList();
    }else {
      proxy.$modal.msgError("左侧字典树编码错误！！");
      return;
    }
  });
}

/** 节点单击事件 */
function dictNodeClick(dict) {
  emit("ok", dict);
};

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const emit = defineEmits(["ok"]);

</script>
<template>
  <div class="head-container">
    <el-input clearable v-model="pd.name" placeholder="请输入查询名称" prefix-icon="Search"/>
  </div>
  <div class="head-container">
    <el-tree :data="pd.dictList" :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false"
             :filter-node-method="filterNode" ref="dictRef" node-key="id" highlight-current default-expand-all
             @node-click="dictNodeClick"/>
  </div>
</template>

<style scoped>

</style>